"""爬取新浪体育网站2023-2024赛季NBA常规赛排名数据"""

import requests
import json
import csv
from bs4 import BeautifulSoup
import time

def get_nba_rank_data():
    """获取NBA东西部球队排名数据"""
    try:
        # 设置请求头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        
        # 获取排名页面URL
        url = 'https://slamdunk.sports.sina.com.cn/'
        
        # 发送GET请求获取页面内容
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        response.encoding = response.apparent_encoding
        
        # 使用BeautifulSoup解析HTML
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 初始化东西部球队数据列表
        east_teams = []
        west_teams = []
        
        # 查找所有包含球队信息的行
        team_rows = soup.find_all('tr')
        
        # 解析东部球队数据
        for row in team_rows:
            cols = row.find_all('td')
            if len(cols) >= 5:  # 确保行中有足够的列数据
                team_data = {
                    'rank': cols[0].text.strip() if cols[0].text.strip() else '',
                    'name': cols[1].text.strip() if cols[1].text.strip() else '',
                    'wins': cols[2].text.strip() if cols[2].text.strip() else '',
                    'losses': cols[3].text.strip() if cols[3].text.strip() else ''
                }
                if '东部' in str(row.previous_sibling) or '东部' in str(row.parent):
                    east_teams.append(team_data)
                elif '西部' in str(row.previous_sibling) or '西部' in str(row.parent):
                    west_teams.append(team_data)
        
        if east_teams or west_teams:
            return {
                'east': east_teams,
                'west': west_teams
            }
        else:
            print('未找到排名数据')
            return None
            
    except requests.RequestException as e:
        print(f'请求失败：{e}')
        return None
    except Exception as e:
        print(f'发生未知错误：{e}')
        return None

def save_to_json(data, filename):
    """将数据保存为JSON文件"""
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
        print(f'数据已成功保存到{filename}')
    except Exception as e:
        print(f'保存JSON文件失败：{e}')

def save_to_csv(data, filename):
    """将数据保存为CSV文件"""
    try:
        with open(filename, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            # 写入表头
            writer.writerow(['联盟', '球队', '排名', '胜场', '负场'])
            # 写入东部球队数据
            for team in data['east']:
                writer.writerow(['东部', team['name'], team['rank'], team['wins'], team['losses']])
            # 写入西部球队数据
            for team in data['west']:
                writer.writerow(['西部', team['name'], team['rank'], team['wins'], team['losses']])
        print(f'数据已成功保存到{filename}')
    except Exception as e:
        print(f'保存CSV文件失败：{e}')

def main():
    # 获取NBA排名数据
    data = get_nba_rank_data()
    
    if data:
        # 保存数据到文件
        save_to_json(data, 'nba_rank.json')
        save_to_csv(data, 'nba_rank.csv')
    else:
        print('获取数据失败，无法保存文件')


if __name__ == '__main__':
    main()
        